package com.gqj.meter.controller;

import com.alibaba.fastjson.JSON;
import com.gqj.common.annotation.Log;
import com.gqj.common.constant.UserConstants;
import com.gqj.common.core.controller.BaseController;
import com.gqj.common.core.domain.AjaxResult;
import com.gqj.common.core.page.TableDataInfo;
import com.gqj.common.enums.BusinessType;
import com.gqj.common.utils.StorageUtil;
import com.gqj.common.utils.poi.ExcelUtil;
import com.gqj.meter.domain.MdConcentrator;
import com.gqj.meter.domain.MdInTaskDetails;
import com.gqj.meter.domain.vo.MdConcentratorVo;
import com.gqj.meter.mapper.MdInTaskDetailsMapper;
import com.gqj.meter.service.IMdConcentratorService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 集中器Controller
 *
 * @author lxq
 * @date lxq-02-10
 */
@Api(value = "/meter/mdConcentrator", description = "采集器")
@RestController
@RequestMapping("/meter/mdConcentrator")
public class MdConcentratorController extends BaseController {
    @Autowired
    private IMdConcentratorService mdConcentratorService;
    @Value("${downloadPath}")
    private String downloadPath;
    @Autowired
    private MdInTaskDetailsMapper mdInTaskDetailsMapper;

    /**
     * 查询集中器列表
     */
    @ApiOperation("查询集中器列表")
    @PreAuthorize("@ss.hasPermi('meter:mdConcentrator:list')")
    @GetMapping("/list")
    public TableDataInfo list(MdConcentrator mdConcentrator) {
        startPage();
        List<MdConcentrator> list = mdConcentratorService.selectMdConcentratorList(mdConcentrator);
        return getDataTable(list);
    }

    /**
     * 导出集中器列表
     */
    @ApiOperation("导出集中器列表")
    @PreAuthorize("@ss.hasPermi('meter:mdConcentrator:export')")
    @Log(title = "采集器", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, MdConcentrator mdConcentrator) {
        List<MdConcentrator> list = mdConcentratorService.selectMdConcentratorList(mdConcentrator);
        ExcelUtil<MdConcentrator> util = new ExcelUtil<MdConcentrator>(MdConcentrator.class);
        util.exportExcel(response, list, "集中器数据");
    }

    /**
     * 获取集中器详细信息
     */
    @ApiOperation("获取集中器详细信息")
    @PreAuthorize("@ss.hasPermi('meter:mdConcentrator:query')")
    @GetMapping(value = "/{concentratorId}")
    public AjaxResult getInfo(@PathVariable("concentratorId") Long concentratorId) {
        return success(mdConcentratorService.selectMdConcentratorByConcentratorId(concentratorId));
    }

    /**
     * 新增集中器
     */
    @ApiOperation("新增集中器")
    @PreAuthorize("@ss.hasPermi('meter:mdConcentrator:add')")
    @Log(title = "采集器", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody MdConcentrator mdConcentrator) {
        if (UserConstants.NOT_UNIQUE.equals(mdConcentratorService.checkRfidNoUnique(mdConcentrator))) {
            return AjaxResult.error("新增'" + mdConcentrator.getRfidNo() + "'失败，条形码已存在！");
        }
        return toAjax(mdConcentratorService.insertMdConcentrator(mdConcentrator));
    }

    /**
     * 修改集中器
     */
    @ApiOperation("修改集中器")
    @PreAuthorize("@ss.hasPermi('meter:mdConcentrator:edit')")
    @Log(title = "采集器", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody MdConcentrator mdConcentrator) {
        if (null == mdConcentrator.getConcentratorId() || 0 == mdConcentrator.getConcentratorId()) {
            return AjaxResult.error("修改失败，集中器ID为空！");
        }
        if (UserConstants.NOT_UNIQUE.equals(mdConcentratorService.checkRfidNoUnique(mdConcentrator))) {
            return AjaxResult.error("修改'" + mdConcentrator.getRfidNo() + "'失败，条形码已存在！");
        }
        return toAjax(mdConcentratorService.updateMdConcentrator(mdConcentrator));
    }

    /**
     * 删除集中器
     */
    @ApiOperation("删除集中器")
    @PreAuthorize("@ss.hasPermi('meter:mdConcentrator:remove')")
    @Log(title = "采集器", businessType = BusinessType.DELETE)
    @DeleteMapping("/{concentratorIds}")
    public AjaxResult remove(@PathVariable Long[] concentratorIds) {

        //判断集中器是否被引用
        for (int i = 0; i < concentratorIds.length; i++) {
            MdConcentrator mdConcentrator = mdConcentratorService.selectMdConcentratorByConcentratorId(concentratorIds[i]);
            //查看盘点单是否引用
            String serviceStatus = mdConcentrator.getServiceStatus();
            if (!"00".equals(serviceStatus) && !"01".equals(serviceStatus) && !"04".equals(serviceStatus)) {
                return AjaxResult.error("采集器" + mdConcentrator.getRfidNo() + "的业务状态不允许删除！");
            }

            //查看出入库是否引用
            MdInTaskDetails mdInTaskDetails = new MdInTaskDetails();
            mdInTaskDetails.setRfidNo(mdConcentrator.getRfidNo());
            mdInTaskDetails.setIsComplete("0");
            List<MdInTaskDetails> mdInTaskDetailsList = mdInTaskDetailsMapper.selectMdInTaskDetailsList(mdInTaskDetails);
            if (mdInTaskDetailsList.size() > 0) {
                return AjaxResult.error("采集器" + mdConcentrator.getRfidNo() + "入库任务中已经引用，无法删除！");
            }
        }
        return toAjax(mdConcentratorService.deleteMdConcentratorByConcentratorIds(concentratorIds));
    }

    /**
     * 下载集中器json文件
     */
    @ApiOperation("下载集中器json文件")
    @PreAuthorize("@ss.hasPermi('meter:mdConcentrator:downloadJsonMdConcentrator')")
    @GetMapping("/downloadJsonMdConcentrator")
    public AjaxResult downloadJsonMdConcentrator(MdConcentrator mdConcentrator) {
        List<MdConcentrator> cms = mdConcentratorService.selectMdConcentratorList(mdConcentrator);
        List<MdConcentratorVo> vos = StorageUtil.copyList(cms, MdConcentratorVo::new);

        String orderNo = StorageUtil.getOrderNoTo12();
        // 生成文件名
        String fileName = downloadPath;
        String jsonStringAc = JSON.toJSONString(vos);
        StorageUtil.createJsonFile(jsonStringAc, fileName, "集中器数据" + orderNo);
        return AjaxResult.success(fileName + "集中器数据" + orderNo);
    }

    /**
     * 导入集中器execl文件
     */
    @ApiOperation("导入集中器execl文件")
    @Log(title = "导入集中器execl文件", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('meter:mdConcentrator:importDataConcentrator')")
    @PostMapping("/importDataConcentrator")
    public AjaxResult importDataConcentrator(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<MdConcentrator> util = new ExcelUtil<MdConcentrator>(MdConcentrator.class);
        List<MdConcentrator> concentratorList = util.importExcel(file.getInputStream());
        String operName = getUsername();
        String message = mdConcentratorService.importConcentrator(concentratorList, updateSupport, operName);
        return success(message);
    }

    @ApiOperation("下载集中器模板")
    @PostMapping("/importTemplateMdConcentrator")
    @PreAuthorize("@ss.hasPermi('meter:mdConcentrator:importTemplateMdConcentrator')")
    public void importTemplateMdConcentrator(HttpServletResponse response) {
        ExcelUtil<MdConcentrator> util = new ExcelUtil<MdConcentrator>(MdConcentrator.class);
        util.importTemplateExcel(response, "集中器数据");
    }
}
